/*
 * Project Name spring-boot-tools
 * File Name MapperExtend
 * Package Name com.huxiaosu.tools.mybatis.handlers
 * Create Time 2024/7/15
 * Create by name：liujie
 */
package com.huxiaosu.tools.mybatis.extend.handlers;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.huxiaosu.tools.common.base.LogonUser;
import com.huxiaosu.tools.common.holder.LogonUserHolder;
import org.apache.ibatis.reflection.MetaObject;

import java.sql.Timestamp;
import java.util.Date;

/**
 * 创建自定义元对象处理器接口
 * 插入和更新的时候自动追加一些信息
 *
 * @author liujie
 * @date 2024/7/15 15:33
 */

public class MapperExtend implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        LogonUser user = LogonUserHolder.get();
        if (user != null) {
            this.setFieldValByName("createUserId", user.getId(), metaObject);
            Object tenantId = getFieldValByName("tenantId", metaObject);
            if (tenantId == null || tenantId == "") {
                this.setFieldValByName("tenantId", user.getTenantId(), metaObject);
            }
        }
        this.setFieldValByName("createDate", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LogonUser user = LogonUserHolder.get();
        if(user == null){
            return;
        }
        // 软删除时，需要外面先 setIsDelete(true)，否则无法识别是更新还是软删除操作
        if (metaObject.hasGetter("deleteMark") && metaObject.getValue("deleteMark") .equals(Boolean.TRUE)) {
            // 软删除更新
            this.setFieldValByName("deleteDate", new Timestamp(System.currentTimeMillis()), metaObject);
            this.setFieldValByName("deleteUserId", user.getId(), metaObject);
        } else {
            this.setFieldValByName("updateDate", new Timestamp(System.currentTimeMillis()), metaObject);
            this.setFieldValByName("updateUserId", user.getId(), metaObject);
        }
    }
}